from faker import Faker
import random
from datetime import datetime, timedelta
from data_mock.utils import FileUtil, MysqlUtils_AI

fake = Faker('zh_CN')

# ========== 癌症相关配置 ==========
CANCER_TYPES = {
    'C34.90': {'name': '肺恶性肿瘤', 'symptoms': ['咳嗽', '咯血', '胸痛', '呼吸困难']},
    'C16.9': {'name': '胃恶性肿瘤', 'symptoms': ['上腹痛', '恶心呕吐', '黑便', '食欲减退']},
    'C18.9': {'name': '结肠恶性肿瘤', 'symptoms': ['腹痛', '便血', '排便习惯改变', '体重下降']},
    'C50.919': {'name': '乳腺恶性肿瘤', 'symptoms': ['乳房肿块', '乳头溢液', '皮肤凹陷', '腋窝淋巴结肿大']},
    'C61': {'name': '前列腺恶性肿瘤', 'symptoms': ['排尿困难', '尿频', '血尿', '骨盆疼痛']}
}

COMMON_DIAGNOSES = {
    'I10': '高血压',
    'E11.9': '2型糖尿病',
    'E78.5': '高脂血症',
    'J18.9': '肺炎',
    'K21.9': '胃食管反流病'
}

TREATMENT_METHODS = {
    '肺恶性肿瘤': ['化疗(培美曲塞+顺铂)', '靶向治疗(吉非替尼)', '放疗', '免疫治疗(帕博利珠单抗)'],
    '胃恶性肿瘤': ['化疗(奥沙利铂+卡培他滨)', '靶向治疗(曲妥珠单抗)', '手术(胃大部切除术)'],
    '结肠恶性肿瘤': ['化疗(FOLFOX方案)', '靶向治疗(贝伐珠单抗)', '手术(结肠癌根治术)'],
    '乳腺恶性肿瘤': ['化疗(多西他赛+环磷酰胺)', '内分泌治疗(他莫昔芬)', '手术(乳腺癌改良根治术)'],
    '前列腺恶性肿瘤': ['内分泌治疗(比卡鲁胺)', '手术(前列腺癌根治术)', '放疗']
}


# ========== 生成函数 ==========
def generate_discharge_records():
    sql_statements = []
    record_sn_counter = 20001  # 记录流水号计数器

    # 生成30天的数据
    for day in generate_day_range("2025-08-01", "2025-08-30"):
        records_per_day = 5 if datetime.strptime(day, "%Y-%m-%d").day % 2 else 7

        for i in range(records_per_day):
            # 选择随机癌症类型
            cancer_code, cancer_info = random.choice(list(CANCER_TYPES.items()))

            # 生成患者基本信息
            patient_id = f"PT{random.randint(1000, 9999)}"
            visit_sn = f"VIS{random.randint(1000, 9999)}"
            record_sn = f"DIS{record_sn_counter}"
            record_sn_counter += 1

            # 生成入院和出院时间（住院天数7-21天）
            admission_date = fake.date_time_between(
                start_date=datetime.strptime(day, "%Y-%m-%d") - timedelta(days=21),
                end_date=datetime.strptime(day, "%Y-%m-%d") - timedelta(days=7)
            )
            discharge_date = admission_date + timedelta(days=random.randint(7, 21))
            record_datetime = discharge_date + timedelta(hours=random.randint(1, 6))

            # 生成诊断信息
            admission_diags = generate_diagnoses(cancer_code, cancer_info['name'])
            discharge_diags = generate_diagnoses(cancer_code, cancer_info['name'])

            # 生成治疗信息
            treatment_info = generate_treatment_info(cancer_info['name'])

            # 构建数据字典
            data = {
                'patient_id': patient_id,
                'visit_sn': visit_sn,
                'record_sn': record_sn,
                'record_datetime': record_datetime.strftime('%Y-%m-%d %H:%M:%S'),
                'medical_record_no': f"MR{random.randint(100000, 999999)}",
                'inpatient_no': f"IP{random.randint(100000, 999999)}",
                'hospitalization_times': str(random.randint(1, 5)),
                'admission_datetime': admission_date.strftime('%Y-%m-%d %H:%M:%S'),
                'discharge_order': generate_discharge_order(cancer_info['name']),
                'discharge_datetime': discharge_date.strftime('%Y-%m-%d %H:%M:%S'),

                # 评分系统
                'kps_score': str(random.randint(50, 90)),
                'ecog_score': str(random.randint(0, 2)),

                # 文书内容
                'record_text': generate_record_text(cancer_info['name'], cancer_code, admission_date, discharge_date),
                'admission_condition': generate_admission_condition(cancer_info['name'], cancer_info['symptoms']),
                'treatment_info': treatment_info,
                'discharge_condition': generate_discharge_condition(cancer_info['name']),

                # 入院诊断
                'admission_maindiag_code1': admission_diags[0]['code'],
                'admission_maindiag_name1': admission_diags[0]['name'],
                'admission_diag_code2': admission_diags[1]['code'] if len(admission_diags) > 1 else None,
                'admission_diag_name2': admission_diags[1]['name'] if len(admission_diags) > 1 else None,
                'admission_diag_code3': admission_diags[2]['code'] if len(admission_diags) > 2 else None,
                'admission_diag_name3': admission_diags[2]['name'] if len(admission_diags) > 2 else None,
                'admission_diag_code4': admission_diags[3]['code'] if len(admission_diags) > 3 else None,
                'admission_diag_name4': admission_diags[3]['name'] if len(admission_diags) > 3 else None,
                'admission_diag_code5': admission_diags[4]['code'] if len(admission_diags) > 4 else None,
                'admission_diag_name5': admission_diags[4]['name'] if len(admission_diags) > 4 else None,
                'admission_diag_coden': "|".join([d['code'] for d in admission_diags[5:]]) if len(
                    admission_diags) > 5 else None,
                'admission_diag_namen': "|".join([d['name'] for d in admission_diags[5:]]) if len(
                    admission_diags) > 5 else None,

                # 出院诊断
                'discharge_maindiag_code1': discharge_diags[0]['code'],
                'discharge_maindiag_name1': discharge_diags[0]['name'],
                'discharge_diag_code2': discharge_diags[1]['code'] if len(discharge_diags) > 1 else None,
                'discharge_diag_name2': discharge_diags[1]['name'] if len(discharge_diags) > 1 else None,
                'discharge_diag_code3': discharge_diags[2]['code'] if len(discharge_diags) > 2 else None,
                'discharge_diag_name3': discharge_diags[2]['name'] if len(discharge_diags) > 2 else None,
                'discharge_diag_code4': discharge_diags[3]['code'] if len(discharge_diags) > 3 else None,
                'discharge_diag_name4': discharge_diags[3]['name'] if len(discharge_diags) > 3 else None,
                'discharge_diag_code5': discharge_diags[4]['code'] if len(discharge_diags) > 4 else None,
                'discharge_diag_name5': discharge_diags[4]['name'] if len(discharge_diags) > 4 else None,
                'discharge_diag_coden': "|".join([d['code'] for d in discharge_diags[5:]]) if len(
                    discharge_diags) > 5 else None,
                'discharge_diag_namen': "|".join([d['name'] for d in discharge_diags[5:]]) if len(
                    discharge_diags) > 5 else None,

                # 系统字段
                'record_status': 1,
                'yy_upload_status': 0,
                'yy_etl_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                'yy_batch_time': day,
                'yy_record_batch_id': f"BATCH{day}_{i}"
            }

            sql = generate_sql('b07_1', data)
            sql_statements.append(sql)

    return sql_statements


# ========== 文书内容生成函数 ==========
def generate_record_text(cancer_name, cancer_code, admission_date, discharge_date):
    hospitalization_days = (discharge_date - admission_date).days
    symptoms = CANCER_TYPES[cancer_code]['symptoms']
    return f"""
出院记录

姓名：{fake.name()}  性别：{random.choice(['男', '女'])}  年龄：{random.randint(30, 80)}岁
住院号：{f"IP{random.randint(100000, 999999)}"}
入院日期：{admission_date.strftime('%Y-%m-%d')}
出院日期：{discharge_date.strftime('%Y-%m-%d')}
住院天数：{hospitalization_days}天

入院诊断：{cancer_name}
出院诊断：{cancer_name}

入院情况：患者因"{random.choice(symptoms)}{random.randint(1, 12)}个月"入院。

诊疗经过：住院期间给予{random.choice(TREATMENT_METHODS[cancer_name])}等治疗，病情{random.choice(['稳定', '部分缓解', '明显好转'])}。

出院情况：患者一般情况{random.choice(['良好', '尚可'])}, {random.choice(['无特殊不适', '症状较前减轻'])}。

出院医嘱：{generate_discharge_order(cancer_name)}
"""


def generate_admission_condition(cancer_name, symptoms):
    main_symptom = random.choice(symptoms)
    duration = f"{random.randint(1, 12)}个月"
    exam_findings = {
        '肺恶性肿瘤': "胸部CT示肺部占位，考虑恶性肿瘤",
        '胃恶性肿瘤': "胃镜示胃部肿物，病理证实为腺癌",
        '结肠恶性肿瘤': "肠镜示结肠肿物，病理证实为腺癌",
        '乳腺恶性肿瘤': "乳腺超声及活检证实为乳腺癌",
        '前列腺恶性肿瘤': "前列腺MRI及活检证实为前列腺癌"
    }
    return f"患者因'{main_symptom}{duration}'就诊，{exam_findings[cancer_name]}。"


def generate_treatment_info(cancer_name):
    primary_treatment = random.choice(TREATMENT_METHODS[cancer_name])
    response = random.choice(['症状明显缓解', '病情稳定', '肿瘤部分缩小'])
    side_effects = random.choice(['耐受良好', '出现轻度不良反应', '出现骨髓抑制'])
    return f"住院期间主要给予{primary_treatment}，治疗反应：{response}。不良反应：{side_effects}。"


def generate_discharge_condition(cancer_name):
    conditions = {
        '肺恶性肿瘤': "咳嗽、胸痛症状较前减轻，肺部病灶较前缩小",
        '胃恶性肿瘤': "上腹痛症状缓解，食欲改善",
        '结肠恶性肿瘤': "腹痛减轻，排便情况改善",
        '乳腺恶性肿瘤': "乳房肿块缩小，疼痛减轻",
        '前列腺恶性肿瘤': "排尿困难改善，PSA水平下降"
    }
    return conditions[cancer_name] + f"，KPS评分{random.randint(60, 90)}分。"


def generate_discharge_order(cancer_name):
    follow_up = {
        '肺恶性肿瘤': "每3个月复查胸部CT",
        '胃恶性肿瘤': "每3个月复查胃镜",
        '结肠恶性肿瘤': "每6个月复查肠镜",
        '乳腺恶性肿瘤': "每3个月复查乳腺超声",
        '前列腺恶性肿瘤': "每3个月复查PSA"
    }
    medications = {
        '肺恶性肿瘤': "继续口服靶向药物",
        '胃恶性肿瘤': "继续口服化疗药物",
        '结肠恶性肿瘤': "继续口服化疗药物",
        '乳腺恶性肿瘤': "继续内分泌治疗",
        '前列腺恶性肿瘤': "继续内分泌治疗"
    }
    return f"""
1. 出院后继续{medications[cancer_name]}
2. {follow_up[cancer_name]}
3. 如有不适，及时就诊
"""


def generate_diagnoses(primary_code, primary_name):
    diagnoses = [{'code': primary_code, 'name': primary_name}]
    # 添加1-3个合并症
    for _ in range(random.randint(1, 3)):
        code, name = random.choice(list(COMMON_DIAGNOSES.items()))
        diagnoses.append({'code': code, 'name': name})
    return diagnoses


# ========== 辅助函数 ==========
def generate_day_range(start_date, end_date):
    start = datetime.strptime(start_date, "%Y-%m-%d")
    end = datetime.strptime(end_date, "%Y-%m-%d")
    delta = end - start
    return [(start + timedelta(days=i)).strftime("%Y-%m-%d") for i in range(delta.days + 1)]


def generate_sql(table, data):
    columns = []
    values = []
    for k, v in data.items():
        columns.append(f"`{k}`")
        if v is None:
            values.append("NULL")
        elif isinstance(v, (int, float)):
            values.append(str(v))
        else:
            escaped_value = str(v).replace("'", "''")
            values.append(f"'{escaped_value}'")
    return f"INSERT INTO `{table}` ({', '.join(columns)}) VALUES ({', '.join(values)});"


# ========== 执行生成 ==========
if __name__ == "__main__":
    print("开始生成出院记录数据...")
    records = generate_discharge_records()
    # 写入数据库
    MysqlUtils_AI.insert_data_to_hub(records, 'b07_1')
    print(f"成功生成{len(records)}条出院记录数据")